﻿var lsInfo = {
  current: 1,
  pageSize: allPageSize,
  data: [],
  totalRow: 0,
  totalPage: 0,
  oneDate: {},
  editState: false,
  state: 0
};

var td3Arr = [];
var tdx = {
  td2: [],
  td3: []
};

// document.getElementById('nav').innerHTML = template('navs', navinfo1);

$('#nav li').eq(1).addClass('active');

var getList = function (obj) {
  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=PDGetProjectsByPass',
    type: 'get',
    data: {
      ProjectName: searchObj.ProjectName,
      StartDate: searchObj.StartDate,
      EndDate: searchObj.EndDate,
      sorts: ' StartDate DESC',
      pagesize: obj.size,
      page: obj.index
    },
    dataType: 'json',
    success: function (data) {
      // console.log(data)
      if (data.Success) {
        obj.callback(data)
      }
    }
  });
};

getList({
  size: lsInfo.pageSize,
  index: lsInfo.current,
  callback: function (data) {
    // console.log(JSON.stringify(data));
    var newData = data.ApiParamObj[0];
    for (var key in newData) {
      newData[key].StartDate = new Date(newData[key].StartDate).pattern('yyyy/MM/dd');
      newData[key].EndDate = new Date(newData[key].EndDate).pattern('yyyy/MM/dd');
      if (newData[key]['State'] === '????') {
        newData[key]['State'] = '';
      }
    }
    // 列表数据
    document.getElementById('listTable').innerHTML = template('staffList', newData);
    // 分页
    var pagesInfo = data.ApiParamObj[1];
    lsInfo.data = newData;
    lsInfo.totalRow = pagesInfo[0].totalRow;
    lsInfo.totalPage = pagesInfo[0].totalPage;

    $('#totalRow').html(lsInfo.totalRow);
    pagesSet(lsInfo);
    setPageSize(lsInfo);
    loading.hide();
  }
});

// 点击分页请求事件
var showPage = function (o) {
  getList({
    size: o.pageSize,
    index: o.current,
    callback: function (data) {
      // console.log(JSON.stringify(data));
      var newData = data.ApiParamObj[0];
      for (var key in newData) {
        newData[key].StartDate = new Date(newData[key].StartDate).pattern('yyyy/MM/dd');
        newData[key].EndDate = new Date(newData[key].EndDate).pattern('yyyy/MM/dd');
        if (newData[key]['State'] === '????') {
          newData[key]['State'] = '';
        }
      }
      // 列表数据
      document.getElementById('listTable').innerHTML = template('staffList', newData);
      // 分页
      var pagesInfo = data.ApiParamObj[1];
      o.data = newData;
      o.totalRow = pagesInfo[0].totalRow;
      o.totalPage = pagesInfo[0].totalPage;

      $('#totalRow').html(o.totalRow);
      pagesSet(o);
      loading.hide();
    }
  });
};


// 人员配置
$('#table').on('click', '.staffing', function () {
  var _this = $(this);
  var index = _this.parent().parent().index();
  lsInfo.oneDate = lsInfo.data[index];
  // console.log(lsInfo.oneDate);
  $('#projectStaff').modal('show');

  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=PDGetProjectUsers',
    type: 'get',
    data: {
      'ProjectID': lsInfo.oneDate.ID
    },
    dataType: 'json',
    success: function (data) {
      // console.log(data)
      // console.log(JSON.stringify(data));
      if (data.Success) {
        // console.log(JSON.stringify(data));
        // console.log(JSON.stringify(lsInfo.oneDate));
        var obj = {};
        var list = data.ApiParamObj;
        var i = 0;
        var l = list.length;
        var h;
        var v = [];
        var selected = '';

        for (; i < l; i++) {
          if (!obj[list[i].PositionNameCN]) {
            obj[list[i].PositionNameCN] = [];
          }
          obj[list[i].PositionNameCN].push(list[i]);
        }
        // console.log(obj)
        i = 0;
        v = obj['项目经理'];
        l = v.length;
        h = '';
        var s = false;
        for (; i < l; i++) {
          if (v[i].IsAllot !== '未分配' && v[i].RoleType === 'PM') {
            selected = 'selected="selected"';
            s = true;
          } else {
            selected = '';
          }
          // console.log(selected)
          h += '<option value="' + v[i].UserId + '" ' + selected + '>' + v[i].UserName + '</option>';
        }
        $('#td1').html(h);
        // console.log(s)
        if (!s) {
          // console.log(3)
          var v1Selected = '';
          i = 0;
          v = obj['项目经理'];
          l = v.length;
          for (; i < l; i++) {
            // console.log(v[i].UserName, v[i].UserId, lsInfo.oneDate.PrincipalName, lsInfo.oneDate.CreatorName)
            // console.log(v[i].UserName, v[i].UserId, lsInfo.oneDate.PrincipalName, lsInfo.oneDate.CreatorName)
            if (v[i].UserName === lsInfo.oneDate.PrincipalName) {
              v1Selected = v[i].UserId;
              break;
            } else if (v[i].UserName === lsInfo.oneDate.CreatorName) {
              v1Selected = v[i].UserId;
              break;
            }

          }
          // console.log(v1Selected)

          $('#td1').select2().val(v1Selected).trigger('change');
        }

        td3Arr = [];
        tdx = {
          td2: [],
          td3: []
        };

        // i = 0;
        // v = obj['运营执行'];
        // l = v.length;
        // h = '<option></option>';
        // for (; i < l; i++) {
        //   if (v[i].IsAllot !== '未分配' && v[i].RoleType === 'RUN') {
        //     selected = 'selected="selected"';
        //   } else {
        //     selected = '';
        //   }
        //   h += '<option value="' + v[i].UserId + '" ' + selected + '>' + v[i].UserName + '</option>';
        // }
        // $('#td2').html(h);

        i = 0;
        // v = obj['岗位培训讲师'];
        v = list;
        l = v.length;
        var h21 = '<option></option>';
        var h31 = '<option></option>';
        var h2 = '';
        var h3 = '';


        for (; i < l; i++) {
          switch (v[i].PositionNameCN) {
            case '运营执行':
              if (v[i].IsAllot !== '未分配' && v[i].RoleType === 'RUN') {
                h2 += '<a><span class="del">x</span>' + v[i].UserName + '</a>';
                tdx.td2.push(v[i].UserId);
                //   selected = 'selected="selected"';
                // } else {
                //   selected = '';
              }
              h21 += '<option value="' + v[i].UserId + '">' + v[i].UserName + '</option>';
              continue;
              break;
            case '项目经理':
              continue;
              break;
            default:
              if (v[i].IsAllot !== '未分配' && v[i].RoleType === 'PP') {
                h3 += '<a><span class="del">x</span>' + v[i].UserName + '</a>';
                tdx.td3.push(v[i].UserId);
                //   selected = 'selected="selected"';
                // } else {
                //   selected = '';
              }
              h31 += '<option value="' + v[i].UserId + '">' + v[i].UserName + '</option>';
          }
        }
        $('#peopleList').html(h2);
        $('#td2').html(h21);

        $('#teacherList').html(h3);
        $('#td3').html(h31);

        $('#td1').select2();
        $('#td2').select2();
        $('#td3').select2();


        $('.tdx').on('change', function () {
          var id = $(this).attr('id');

          var val = $(this).find(':selected').val();
          if (!val) {
            return false;
          }
          tdx[id].push(val);
          tdx[id] = unique(tdx[id]);
          // console.log(td3Arr);

          i = 0;
          l = tdx[id].length;
          // var hArr = [];
          h = '';
          // console.log(v)
          for(;i < l;i++) {
            for (var key in v) {
              // console.log(v[key], td3Arr[i])
              if (v[key].UserId === tdx[id][i]) {

                // hArr.push(v[key].UserName);
                h += '<a><span class="del">x</span>' + v[key].UserName + '</a>';
              }
            }
          }
          $(this).parent().children('.peopleList').html(h);
          // $('#teacherList').html(h);
        });

        // $('#td2').select2().val(['68de21df-68a1-43b7-b4e9-0957f599aa2c']).trigger('change');
        // console.log(obj, lsInfo.oneDate.PrincipalName)
        /*i = 0;
        v = obj['项目经理'];
        l = v.length;
        var v1Selected = '';
        for (; i < l; i++) {
          if (v[i].UserName === '胡跃辉') {
            v1Selected = v[i].UserId;
            break;
          }
        }


        $('#td1').select2().val(v1Selected).trigger('change');*/

        // var arr3 = '王若楠, 陈玥驱'.split(', ');
        // i = 0;
        // v = obj['运营执行'];
        // l = v.length;
        // var v2Selected = [];
        // for (; i < l; i++) {
        //   if (arr3.indexOf(v[i].UserName) !== -1) {
        //     v2Selected.push(v[i].UserId);
        //   }
        // }

        // $('#td2').select2().val(v2Selected).trigger('change');
      }
    }
  });
});

$('.peopleList').on('click', '.del', function () {
  var ids = $(this).parent().parent().attr('id');
  // console.log(ids)
  var id = ids === 'peopleList' ? 'td2' : 'td3';
  var index = $(this).parent().index();
  $(this).parent().remove();
  tdx[id].splice(index, 1);
});

$('#saveStaff').on('click', function () {
  var arr = [];
  var form = $('#projectStaff form');
  var v1 = $('#td1 :selected').val();

  // var v2 = '';
  // $('#td2 :selected').each(function () {
  //   arr.push($(this).val());
  // });
  // v2 = arr;
  var v2 = tdx.td2;

  // var v3 = '';
  // arr = [];
  // $('#td3 :selected').each(function () {
  //   arr.push($(this).val());
  // });
  // v3 = arr;
  var v3 = tdx.td3;
  // console.log(v2);
  // console.log(v3);

  // return false;
  var validator = new Validator();
  validator.add(v1, [{
    strategy: 'isNonEmpty',
    errorMsg: '项目经理不能为空'
  }]);

  validator.add(v2, [{
    strategy: 'isNonEmpty',
    errorMsg: '项目运营不能为空'
  }]);

  validator.add(v3, [{
    strategy: 'isNonEmpty',
    errorMsg: '老师不能为空'
  }]);

  var errmsg = validator.start();
  if (errmsg) {
    alert(errmsg);
    return false;
  }

  var t2 = [];
  for (var key in v2) {
    t2.push('RUN');
  }

  var t3 = [];
  for (var key in v3) {
    t3.push('PP');
  }

  var submitData = {
    PD_UserID: v1,
    ProjectID: lsInfo.oneDate.ID,
    StrUserType: ['PM'].concat(t2).concat(t3).join(','),
    StrUserID: [v1].concat(v2).concat(v3).join(',')
  };
  // console.log(submitData);
  // return false;
  loading.show();
  $.ajax({
    url: '/api/CommonApi?API=ProjectUserAllot',
    type: 'post',
    data: {
      ApiParamObj: JSON.stringify(submitData)
    },
    dataType: 'json',
    success: function (data) {
      if (data.Success) {
        console.log('success');
        showPage(lsInfo);
        $('#projectStaff').modal('hide');
        loading.hide();
      }
    }
  });
});